from rest_framework import serializers
from .models import Customer, Product, Order, Host_order
from apps.UMM.models import User, CommissionCategory
from apps.UMM.serializers import UserSerializer, CommissionCategorySerializer
import logging

logger = logging.getLogger(__name__)

class CustomerSerializer(serializers.ModelSerializer):
    # 添加关联订单列表
    orders = serializers.SerializerMethodField()
    
    class Meta:
        model = Customer
        fields = '__all__'
    
    def get_orders(self, obj):
        """获取与客户关联的订单列表，包含ID和订单号"""
        orders = Order.objects.filter(customer_name=obj).values('id', 'order_number')
        return orders

class ProductSerializer(serializers.ModelSerializer):
    commission_category_name = serializers.CharField(source='commission_category.commission_category', read_only=True)
    
    class Meta:
        model = Product
        fields = '__all__'

class OrderListSerializer(serializers.ModelSerializer):
    customer_name_display = serializers.CharField(source='customer_name.customer_name', read_only=True)
    product_name_display = serializers.CharField(source='product_name.product_name', read_only=True)
    nickname_display = serializers.CharField(source='nickname.nickname', read_only=True)
    order_source_display = serializers.CharField(source='get_order_source_display', read_only=True)
    purchase_years_display = serializers.CharField(source='get_purchase_years_display', read_only=True)
    order_status_display = serializers.CharField(source='get_order_status_display', read_only=True)
    expiration_date = serializers.SerializerMethodField()
    
    class Meta:
        model = Order
        fields = '__all__'
    
    def get_expiration_date(self, obj):
        """计算到期日期"""
        if obj.activation_date and obj.purchase_years > 0:
            import datetime
            return obj.activation_date + datetime.timedelta(days=365 * obj.purchase_years)
        return None

class OrderCreateUpdateSerializer(serializers.ModelSerializer):
    class Meta:
        model = Order
        fields = '__all__'
    
    def create(self, validated_data):
        """自动计算提成"""
        order = Order(**validated_data)
        
        # 只有在订单状态为"已激活"时计算提成
        order_status = validated_data.get('order_status')
        if order_status == 1:  # 已激活
            # 获取产品的提成分类比例
            product = validated_data.get('product_name')
            if product:
                commission_ratio = product.commission_category.commission_ratio
                order_amount = validated_data.get('order_amount')
                if order_amount:
                    # 计算提成
                    commission = order_amount * commission_ratio
                    # 检查是否双倍提成
                    if validated_data.get('is_double_coms') == 1:
                        commission *= 2
                    order.commission = commission
        
        return super().create(validated_data)
    
    def update(self, instance, validated_data):
        """自动更新提成金额"""
        # 只有在订单状态为"已激活"时计算提成
        order_status = validated_data.get('order_status', instance.order_status)
        
        if order_status == 1:  # 已激活
            # 获取产品的提成分类比例
            product = validated_data.get('product_name', instance.product_name)
            order_amount = validated_data.get('order_amount', instance.order_amount)
            is_double_coms = validated_data.get('is_double_coms', instance.is_double_coms)
            
            if product:
                commission_ratio = product.commission_category.commission_ratio
                if order_amount:
                    # 计算提成
                    commission = order_amount * commission_ratio
                    # 检查是否双倍提成
                    if is_double_coms == 1:
                        commission *= 2
                    validated_data['commission'] = commission
        
        return super().update(instance, validated_data)

class HostOrderListSerializer(serializers.ModelSerializer):
    """主机出租订单列表序列化器"""
    customer_display = serializers.CharField(source='customer.customer_name', read_only=True)
    nickname_display = serializers.CharField(source='nickname.nickname', read_only=True)
    order_source_display = serializers.CharField(source='get_order_source_display', read_only=True)
    
    # 格式化日期字段
    effective_date = serializers.DateField(format='%Y-%m-%d')
    expiry_date = serializers.DateField(format='%Y-%m-%d')
    creation_date = serializers.DateTimeField(format='%Y-%m-%d %H:%M:%S')
    last_modification_date = serializers.DateTimeField(format='%Y-%m-%d %H:%M:%S')
    
    class Meta:
        model = Host_order
        fields = '__all__'
        depth = 1  # 增加深度，返回关联对象的详细信息

class HostOrderCreateUpdateSerializer(serializers.ModelSerializer):
    """主机出租订单创建和更新序列化器"""
    
    class Meta:
        model = Host_order
        fields = '__all__'
        
    def validate_customer(self, value):
        """确保客户ID是有效的"""
        logger.info(f"验证客户ID: {value} (类型: {type(value)})")
        
        if value is None:
            return None
            
        try:
            # 如果value已经是Customer实例，直接返回
            if isinstance(value, Customer):
                logger.info(f"客户是Customer实例: {value}")
                return value
                
            # 尝试查找客户
            customer = Customer.objects.get(pk=value)
            logger.info(f"找到客户: {customer.customer_name}")
            return customer  # 返回客户对象
        except Customer.DoesNotExist:
            logger.error(f"客户ID不存在: {value}")
            raise serializers.ValidationError("指定的客户不存在")
        except Exception as e:
            logger.error(f"验证客户ID时发生错误: {str(e)}")
            raise serializers.ValidationError(f"验证客户数据时发生错误: {str(e)}")
            
    def validate_nickname(self, value):
        """确保对接人ID是有效的"""
        logger.info(f"验证对接人ID: {value} (类型: {type(value)})")
        
        if value is None:
            return None
            
        try:
            # 如果value已经是User实例，直接返回
            if isinstance(value, User):
                logger.info(f"对接人是User实例: {value}")
                return value
                
            # 尝试查找用户
            user = User.objects.get(pk=value)
            logger.info(f"找到对接人: {user.nickname}")
            return user  # 返回用户对象
        except User.DoesNotExist:
            logger.error(f"对接人ID不存在: {value}")
            raise serializers.ValidationError("指定的对接人不存在")
        except Exception as e:
            logger.error(f"验证对接人ID时发生错误: {str(e)}")
            raise serializers.ValidationError(f"验证对接人数据时发生错误: {str(e)}")
        
    def to_internal_value(self, data):
        """转换输入的数据为内部表示"""
        logger.info(f"输入数据: {data}")
        
        # 将客户ID和对接人ID转换为整数，如果是字符串的话
        data_copy = data.copy() if hasattr(data, 'copy') else dict(data)
        
        # 处理客户ID
        if 'customer' in data_copy and data_copy['customer'] and not data_copy['customer'] == '':
            try:
                if not isinstance(data_copy['customer'], Customer) and not isinstance(data_copy['customer'], int):
                    data_copy['customer'] = int(data_copy['customer'])
                    logger.info(f"转换客户ID为整数: {data_copy['customer']}")
            except (ValueError, TypeError) as e:
                logger.error(f"无法将客户ID转换为整数: {data_copy['customer']}, 错误: {str(e)}")
                
        # 处理对接人ID
        if 'nickname' in data_copy and data_copy['nickname'] and not data_copy['nickname'] == '':
            try:
                if not isinstance(data_copy['nickname'], User) and not isinstance(data_copy['nickname'], int):
                    data_copy['nickname'] = int(data_copy['nickname'])
                    logger.info(f"转换对接人ID为整数: {data_copy['nickname']}")
            except (ValueError, TypeError) as e:
                logger.error(f"无法将对接人ID转换为整数: {data_copy['nickname']}, 错误: {str(e)}")
        
        return super().to_internal_value(data_copy)
    
    def create(self, validated_data):
        """创建主机出租订单"""
        logger.info(f"创建主机出租订单，数据: {validated_data}")
        return super().create(validated_data)
    
    def update(self, instance, validated_data):
        """更新主机出租订单"""
        logger.info(f"更新主机出租订单，ID: {instance.id}, 数据: {validated_data}")
        return super().update(instance, validated_data) 